package com.qf.question01.service.impl;


import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.digest.DigestUtil;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.question01.dao.UserDao;
import com.qf.question01.entity.User;
import com.qf.question01.ex.UserException;
import com.qf.question01.service.UserService;
import com.qf.question01.vo.ResultVo;
import com.qf.question01.vo.TableVo;
import com.qf.question01.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Value("${qfsy.filepath}")
    String filepath;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    UserDao userDao;
    private Exception Exception;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public User login(String username, String password) {
        //1. 根据用户名查询用户信息
        User user =  userDao.getUserByName(username);

        if (user == null){  // 没用匹配的用户，直接返回null
            return null;
        }else {
            //2. 比对密码是否正确
            final String dbpassword = user.getPassword();

            // 转换 password 为 md5 字符串
            final String md5password = DigestUtil.md5Hex(password);

            if (dbpassword.equals(md5password)){
                return user;
            }

            return null;
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVo regist(UserRegistVo userRegistVo) throws IOException {

        User userByName = userDao.getUserByName(userRegistVo.getUsername());

        if (userByName!=null){
        return ResultVo.error("用户已存在");
        }

        MultipartFile photo = userRegistVo.getPhoto();

        String filename = photo.getOriginalFilename();

        String randFile = UUID.randomUUID().toString();

        String finalPath = filepath+"_"+randFile+"_"+filename;

        photo.transferTo(new File(finalPath));

        String password = DigestUtil.md5Hex(userRegistVo.getPassword());

        User user = new User(null,userRegistVo.getUsername(),password,userRegistVo.getSex(),
                    userRegistVo.getDate(),new Date(),finalPath);

        userDao.insertByUser(user);

        ResultVo resultVo = ResultVo.ok();


        return resultVo;
    }


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public TableVo<User> getAllUsersByPageHelper(Integer page, Integer limit, String username, String sex, Date birthday) {

        final User userCondition = new User();
        userCondition.setName(username);
        userCondition.setSex(sex);
        userCondition.setBirthday(birthday);

        PageHelper.startPage(page,limit); // 设置分页插件查询的页号和页大小
        List<User> data = userDao.getAllUsersByCondition(userCondition);

        final PageInfo<User> pageInfo = new PageInfo<>(data);
        final long total = pageInfo.getTotal();

        return TableVo.ok((int) total,data);


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUser(User user) throws UserException {
        //1. 判断用户名是否存在
        final String uname = user.getName();
        final User dbuser = userDao.getUserByName(uname);
        if (dbuser!=null){
            throw new UserException(-1001,"用户名重复");
        }
        //2. 密码处理
        final String md5Password = DigestUtil.md5Hex(user.getPassword());
        user.setPassword(md5Password);

        //3. 落库
        userDao.insertByUser(user);

    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delUserByIds(String[] ids) {

        userDao.deleteUserByIds(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserById(User user) throws UserException {
        final Integer id = user.getId();
        if (id == null){
            throw new UserException(-1002,"修改用户没传id");
        }

        // 判断密码是否被修改了
        final String password = user.getPassword();
        final User dbuser = userDao.getUserById(id);
        final String dbpassword = dbuser.getPassword();

        if (!dbpassword.equals(password)){
            final String md5Pass = DigestUtil.md5Hex(password);
            if (md5Pass.equals(dbpassword)){
                // 没改密码
                throw new UserException(-1003,"密码跟原密码一致");
            }else {  // 写了新的密码跟原理的md5不一致了
                user.setPassword(md5Pass);
            }
        }

        //2. 更新用户数据
        userDao.updateUserById(user);
    }

    @Override
    public String export() {
            List<User> allUsers = userDao.getAllUsers();
            String uuid = UUID.randomUUID().toString()+".csv";
            String filename =uuid;
            CsvWriter writer = CsvUtil.getWriter(filepath+filename, CharsetUtil.CHARSET_UTF_8);
            writer.writeBeans(allUsers);
            return filename;

    }

    @Override
    public ResultVo upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String randName = UUID.randomUUID().toString();
        String finalName =filepath+"-"+randName+"-"+originalFilename;
        try {
            file.transferTo(new File(finalName));
        }catch (Exception e){
          return   ResultVo.error();
        }
            return ResultVo.ok();
    }

}
